package com.jielihaofeng.netty.eventloop;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @author Johnnie Wind
 * @description EventLoopServer 演示
 * @date 2021/11/9 12:08
 */
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {

        // 处理耗时较长的操作，避免nio的worker处理耗时操作
        DefaultEventLoopGroup group = new DefaultEventLoopGroup(2);
        new ServerBootstrap()
                // Netty建议把职责划分更细，boss 和 worker
                // 细分1：boss 只负责 ServerSocketChannel 上 accept 事件     worker 只负责 socketChannel 上的读写
                // boss不写参数没问题，只会有一个线程绑定，worker暂时设置2测试
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(
                        new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast("handler-1",new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                        ByteBuf byteBuf = (ByteBuf) msg;
                                        log.debug(byteBuf.toString(Charset.defaultCharset())); // 一般不用默认字符集，可能客户端和服务器不在一起
                                        ctx.fireChannelRead(msg); // 让消息传给下一个handler，否则无法传给handler-2
                                    }
                                });
                                // 非IO Group
                                ch.pipeline().addLast(group,"handler-2",new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                        ByteBuf byteBuf = (ByteBuf) msg;
                                        log.debug(byteBuf.toString(Charset.defaultCharset())); // 一般不用默认字符集，可能客户端和服务器不在一起
                                    }
                                });
                            }
                        }
                )
                .bind(8088);
    }
}
